<script setup>
import { onMounted, reactive, ref, toRefs } from "vue";
import Sidentify from "@/util/Sidentify.vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";

// 获取路由
const router = useRouter();

let sidentifyMode = ref(""); //输入框验证码
let identifyCode = ref(""); //图形验证码
let identifyCodes = ref("1234567890");
onMounted(() => {
  identifyCode.value = "";
  makeCode(identifyCodes.value, 4);
});

// 生成随机数
const randomNum = (min, max) => {
  max = max + 1;
  return Math.floor(Math.random() * (max - min) + min);
};
// 随机生成验证码字符串
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)];
  }
};
// 更新验证码
const refreshCode = () => {
  identifyCode.value = "";
  makeCode(identifyCodes.value, 4);
};

const login_status = ref(true);
const text = ref("获取验证码");
// 定义方法，切换登录方式
const accWay = (sta) => {
  login_status.value = sta; // 使用 .value 来访问或修改 ref 的值
  // console.log(login_status.value);
};

// login_use登录角色：3用户0总管理员1调度员2教练
// acc：账号
// pwd：密码
const login_from1 = reactive({
  login_use: "3",
  acc: "",
  pwd: "",
  pho: "",
  code: "",
});

// 输入框是否符合条件标记符
var nameInput2 = false;
var accInput2 = false;
var pwdInput2 = false;
var pwd2Input2 = false;
var phoInput2 = false;

// 注册表单
const regist_from = reactive({
  name: "",
  acc: "",
  pwd: "",
  pwd2: "",
  pho: "",
  code: "",
});

// 检查注册账号
const checkAcc_r = () => {
  if (!regex1.test(regist_from.acc)) {
    accInput2 = false;
    open(
      "账号必须以字母或下划线开头，可包含字母、数字和下划线，长度在4到20个字符之间",
      "error"
    );
  } else {
    // 检验账号是否重复
    axios({
      url: "http://localhost:8080/check",
      method: "post",
      data: {
        account: regist_from.acc,
        phone: regist_from.pho,
        name: regist_from.name,
      },
      headers: {
        "Content-type": "application/json", // 默认
        //   "Content-type": "application/x-www-form-urlencoded",
      },
    })
      .then((res) => {
        if (res.data.code == 0) {
          if (res.data.data.account) {
            accInput2 = ref("true");
            open("账号可以注册", "success");
          } else {
            accInput2 = ref("false");
            open("账号重复", "error");
          }
        } else {
          open("系统错误", "error");
        }
      })
      .catch((err) => {
        open("后台系统错误", "error");
      });
  }
};
const nameRegist = /^.{3,10}$/;

//检查用户名
const checkName_r = () => {
  if (!nameRegist.test(regist_from.name)) {
    nameInput2 = false;
    open("用户名长度在3到10个字符之间", "error");
  } else {
    // 检验账号是否重复
    axios({
      url: "http://localhost:8080/check",
      method: "post",
      data: {
        account: regist_from.acc,
        phone: regist_from.pho,
        name: regist_from.name,
      },
      headers: {
        "Content-type": "application/json", // 默认
        //   "Content-type": "application/x-www-form-urlencoded",
      },
    })
      .then((res) => {
        if (res.data.code == 0) {
          if (res.data.data.name) {
            nameInput2 = ref("true");
            open("用户名可以注册", "success");
          } else {
            nameInput2 = ref("false");
            open("用户名重复", "error");
          }
        } else {
          open("系统错误", "error");
        }
      })
      .catch((err) => {
        open("后台系统错误", "error");
      });
  }
};
//检查手机
const checkPhone_r = () => {
  if (!phonePattern.test(regist_from.pho)) {
    phoInput2 = false;
    open("手机格式错误", "error");
  } else {
    // 检验账号是否重复
    axios({
      url: "http://localhost:8080/check",
      method: "post",
      data: {
        account: regist_from.acc,
        phone: regist_from.pho,
        name: regist_from.name,
      },
      headers: {
        "Content-type": "application/json", // 默认
        //   "Content-type": "application/x-www-form-urlencoded",
      },
    })
      .then((res) => {
        if (res.data.code == 0) {
          if (res.data.data.phone) {
            phoInput2 = ref("true");
            open("手机号可以注册", "success");
          } else {
            phoInput2 = ref("false");
            open("手机号重复", "error");
          }
        } else {
          open("系统错误", "error");
        }
      })
      .catch((err) => {
        open("后台系统错误", "error");
      });
  }
};

// 输入框是否符合条件标记符
var accInput = false;
var pwdInput = false;
var phoInput = false;
const regex1 = /^[a-zA-Z_][a-zA-Z0-9_]{3,19}$/;
// 检查账号
const checkAcc = () => {
  if (!regex1.test(login_from1.acc)) {
    accInput = false;
    open(
      "账号必须以字母或下划线开头，可包含字母、数字和下划线，长度在4到20个字符之间",
      "error"
    );
  } else {
    accInput = ref("true");
    open("账号格式正确", "success");
  }
};

// 检验密码
const regex2 = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,18}$/;
const checkPwd = () => {
  if (!regex2.test(login_from1.pwd)) {
    open(
      "密码必须至少包含一个大写字母、一个小写字母和一个数字，长度至少为8个字符",
      "error"
    );
    pwdInput = ref("false");
  } else if (login_from1.pwd.includes(login_from1.acc)) {
    open("密码不应包含用户名", "error");
    pwdInput = ref("false");
  } else {
    open("密码格式正确", "success");
    pwdInput = ref("true");
  }
};

const checkPwd_r = () => {
  if (!regex2.test(regist_from.pwd)) {
    open(
      "密码必须至少包含一个大写字母、一个小写字母和一个数字，长度至少为8个字符",
      "error"
    );
    pwdInput2 = ref("false");
  } else if (regist_from.pwd.includes(regist_from.acc)) {
    open("密码不应包含用户名", "error");
    pwdInput2 = ref("false");
  } else {
    open("密码格式正确", "success");
    pwdInput2 = ref("true");
  }
};

const checkPwd_r2 = () => {
  if (regist_from.pwd2 != regist_from.pwd) {
    open("两次密码不一致", "error");
    pwd2Input2 = ref("false");
  } else {
    open("两次密码一致", "success");
    pwd2Input2 = ref("true");
  }
};
const getCode2 = () => {
  if (phoInput2) {
    axios({
      url: "http://localhost:8080/getCode2",
      method: "post",
      data: {
        phone: regist_from.pho,
      },
      headers: {
        "Content-type": "application/json", // 默认
        //   "Content-type": "application/x-www-form-urlencoded",
      },
    })
      .then((res) => {
        if (res.data.code == 0) {
          open("验证码发送成功", "success");
          code = res.data.data.code;
          console.log(res, code);
          const interval = setInterval(() => {
            if (timedown > 0) {
              timedown--;
              text.value = timedown + "s后获取";
              counting.value = true;
            } else {
              clearInterval(interval);
              counting.value = false;
              timedown = 60;
              text.value = "获取验证码";
            }
          }, 1000);
        } else {
          open("手机已经注册，请直接登录", "warning");
        }
      })
      .catch((res) => {
        ElMessage({
          message: "系统错误",
          type: "error",
          duration: 1500,
        });
        console.log(res);
      });
  } else {
    open("手机号码格式不正确", "error");
  }
};

const login_submit = () => {
  if (login_status.value == true) {
    // 账号密码登录
    if (!(accInput && pwdInput)) {
      open("账号密码错误", "error");
    } else if (sidentifyMode.value != identifyCode.value) {
      // 判断验证码是否正确
      open("验证码错误" + sidentifyMode.value + "aa" + identifyCode.value, "error");
    } else {
      axios({
        url: "http://localhost:8080/loginAcc",
        method: "post",
        data: {
          loginUse: login_from1.login_use,
          account: login_from1.acc,
          password: login_from1.pwd,
        },
        headers: {
          "Content-type": "application/json", // 默认
          //   "Content-type": "application/x-www-form-urlencoded",
        },
      })
        .then((res) => {
          // console.log(res);
          if (res.data.code == 0) {
            ElMessage({
              message: "登录成功,即将跳转",
              type: "success",
              duration: 1500,
            });
            localStorage.setItem("token", res.data.data.mytoken);
            localStorage.setItem("info", login_from1.login_use);
            localStorage.setItem("avatar",res.data.data.avatar)
            console.log(localStorage);
            setTimeout(() => {
              router.push("main");
            }, 1500);
          } else {
            ElMessage({
              message: "系统错误",
              type: "error",
              duration: 1500,
            });
          }
        })
        .catch((err) => {
          ElMessage({
            message: "系统错误",
            type: "error",
            duration: 1500,
          });
          console.log(err);
        });
    }
    //   手机号登录
  } else {
    if (code == login_from1.code) {
      axios({
        url: "http://localhost:8080/loginPho",
        method: "post",
        data: {
          phone: login_from1.pho,
        },
        headers: {
          "Content-type": "application/json", // 默认
          //   "Content-type": "application/x-www-form-urlencoded",
        },
      })
        .then((res) => {
          if (res.data.code == 0) {
            ElMessage({
              message: "登录成功,即将跳转",
              type: "success",
              duration: 1500,
            });
            localStorage.setItem("token", res.data.data.mytoken);
            localStorage.setItem("info", login_from1.login_use);
            localStorage.setItem("avatar",res.data.data.avatar)
            console.log(localStorage);
            setTimeout(() => {
              router.push("main");
            }, 1500);
          } else {
            ElMessage({
              message: "系统错误",
              type: "error",
              duration: 1500,
            });
          }
        })
        .catch((res) => {
          ElMessage({
            message: "系统错误",
            type: "error",
            duration: 1500,
          });
          console.log(res);
        });
    } else {
      open("验证码错误", "error");
    }
  }
};
// 手机验证正则
const phonePattern = /^1[3-9]\d{9}$/;
const checkPho = () => {
  if (!phonePattern.test(login_from1.pho)) {
    phoInput = false;
    open("手机号码格式不正确", "error");
  } else {
    phoInput = true;
    open("手机号码格式正确", "success");
  }
};

var timedown = 60;
const counting = ref(false);
// 后端传回的验证码
var code = "";
// 验证数据库里面是不是有这个手机号
const getCode = () => {
  if (phoInput) {
    axios({
      url: "http://localhost:8080/getCode",
      method: "post",
      data: {
        phone: login_from1.pho,
      },
      headers: {
        "Content-type": "application/json", // 默认
        //   "Content-type": "application/x-www-form-urlencoded",
      },
    })
      .then((res) => {
        if (res.data.code == 0) {
          open("验证码发送成功", "success");
          code = res.data.data.code;
          console.log(res, code);
          const interval = setInterval(() => {
            if (timedown > 0) {
              timedown--;
              text.value = timedown + "s后获取";
              counting.value = true;
            } else {
              clearInterval(interval);
              counting.value = false;
              timedown = 60;
              text.value = "获取验证码";
            }
          }, 1000);
        } else {
          open("该手机还未注册，请注册后再尝试", "warning");
        }
      })
      .catch((res) => {
        ElMessage({
          message: "系统错误",
          type: "error",
          duration: 1500,
        });
        console.log(res);
      });
  } else {
    open("手机号码格式不正确", "error");
  }
};

// 弹弹窗信息，验证输入框是否正确
const open = (msg, typ) => {
  ElMessage({
    message: msg,
    grouping: true,
    type: typ,
  });
};

// 判断现在是登录还是注册true为登录，false为注册
const service_sta = ref(true);
const service_way = (sta) => {
  service_sta.value = sta;
};
console.log(service_sta.value);
const back = () => {
  router.push("main");
};
// 注册
const regist_click = () => {
  if (!nameInput2) {
    open("用户名格式错误", "error");
  } else if (!accInput2) {
    open("账号格式错误", "error");
  } else if (!pwdInput2) {
    open("密码格式错误", "error");
  } else if (!pwd2Input2) {
    open("两次密码不一致", "error");
  } else if (!phoInput2) {
    open("手机号格式错误", "error");
  }
  //  else if (code != regist_from.code && code.length > 3) {
  //   open("验证码错误", "error");
  // } 
  else {
    axios({
      url: "http://localhost:8080/regist",
      method: "post",
      data: {
        name: regist_from.name,
        account: regist_from.acc,
        password: regist_from.pwd,
        phone: regist_from.pho,
      },
      headers: {
        "Content-type": "application/json", // 默认
        //   "Content-type": "application/x-www-form-urlencoded",
      },
    })
      .then((res) => {
        if (res.data.code == 0) {
          ElMessage({
            message: "注册成功,即将跳转",
            type: "success",
            duration: 1500,
          });
          localStorage.setItem("token", res.data.data.mytoken);
          localStorage.setItem("info", 3);
          localStorage.setItem("avatar",res.data.data.avatar)
          setTimeout(() => {
            router.push("main");
          }, 1500);
        } else {
          ElMessage({
            message: "系统错误",
            type: "error",
            duration: 1500,
          });
        }
      })
      .catch((res) => {
        ElMessage({
          message: "系统错误",
          type: "error",
          duration: 1500,
        });
        console.log(res);
      });
  }
};
</script>

<template>
  <div class="mian_login">
    <h3 class="title">飞梦飞行俱乐部</h3>
    <p class="title2">你的飞行梦我来成就</p>
    <div :class="service_sta ? 'login_div' : 'none_div'">
      <div>
        <div :class="login_status ? 'login_way1' : 'login_way2'" @click="accWay(true)">
          账号密码登录
        </div>
        <div :class="login_status ? 'login_way2' : 'login_way1'" @click="accWay(false)">
          手机号登录
        </div>
      </div>
      <div>
        <el-radio-group v-model="login_from1.login_use" size="large" style="margin: 20px">
          <el-radio-button label="用户" value="3" />
          <el-radio-button label="教练" value="2" v-if="login_status" />
          <el-radio-button label="调度员" value="1" v-if="login_status" />
          <el-radio-button label="管理员" value="0" v-if="login_status" />
        </el-radio-group>
      </div>
      <div :class="login_status ? '' : 'hiden_way'">
        <div class="input_div">
          <span class="input_span">账 号:</span>
          <input
            type="text"
            class="input_css"
            v-model="login_from1.acc"
            @keyup="checkAcc"
            placeholder="请输入账号"
            maxlength="20"
          />
        </div>
        <div class="input_div">
          <span class="input_span">密 码:</span>
          <input
            type="password"
            class="input_css"
            v-model="login_from1.pwd"
            @keyup="checkPwd"
            placeholder="请输入密码"
            maxlength="20"
          />
        </div>
        <div class="input_div">
          <span class="input_span">验证码:</span>
          <input v-model="sidentifyMode" type="text" class="input_css input_code" />
          <div class="code" @click="refreshCode">
            <Sidentify :identifyCode="identifyCode"></Sidentify>
          </div>
        </div>
      </div>

      <div :class="login_status ? 'hiden_way' : ''">
        <div class="input_div">
          <span class="input_span">手机号:</span>
          <input
            maxlength="11"
            type="text"
            class="input_css"
            v-model="login_from1.pho"
            placeholder="请输入手机号"
            @keyup="checkPho"
          />
        </div>
        <div class="input_div">
          <span class="input_span">验证码:</span>
          <input v-model="login_from1.code" type="text" class="input_css input_code" />
          <el-button type="primary" @click="getCode" :disabled="counting">{{
            text
          }}</el-button>
        </div>
      </div>

      <div class="bottom_div">
        <el-button type="primary" @click="login_submit">登录</el-button>
        <el-button @click="back">返回</el-button>
      </div>

      <p class="to_regist" @click="service_way(false)">没有账号去注册</p>
    </div>

    <!-- 注册盒子 -->
    <div :class="!service_sta ? 'login_div' : 'none_div'">
      <div class="login_way1">用户注册</div>
      <div class="input_div">
        <span class="input_span">用户名:</span>
        <input
          type="text"
          v-model="regist_from.name"
          class="input_css"
          @keyup="checkName_r"
          placeholder="请输入用户名"
          maxlength="10"
        />
      </div>
      <div class="input_div">
        <span class="input_span">账 号:</span>
        <input
          type="text"
          v-model="regist_from.acc"
          class="input_css"
          @keyup="checkAcc_r"
          placeholder="请输入账号"
          maxlength="20"
        />
      </div>
      <div class="input_div">
        <span class="input_span">密 码1:</span>
        <input
          type="password"
          v-model="regist_from.pwd"
          class="input_css"
          @keyup="checkPwd_r"
          placeholder="请输入密码"
          maxlength="20"
        />
      </div>
      <div class="input_div">
        <span class="input_span">密码2:</span>
        <input
          type="password"
          v-model="regist_from.pwd2"
          class="input_css"
          @keyup="checkPwd_r2"
          placeholder="请再次输入密码"
          maxlength="20"
        />
      </div>
      <div class="input_div">
        <span class="input_span">手机号:</span>
        <input
          type="text"
          v-model="regist_from.pho"
          class="input_css"
          @keyup="checkPhone_r"
          placeholder="请输入手机号"
          maxlength="11"
        />
      </div>
      <div class="input_div">
        <span class="input_span">验证码:</span>
        <input type="text" class="input_css input_code" v-model="regist_from.code" />
        <el-button type="primary" @click="getCode2" :disabled="counting">{{
          text
        }}</el-button>
      </div>
      <div class="bottom_div">
        <el-button type="primary" @click="regist_click">注册</el-button>
        <el-button @click="service_way(true)">去登录</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="less">
.mian_login {
  width: 100%;
  height: 100%;
  background-image: url("@/assets/bj4.jpg");
  background-size: cover;
  .none_div {
    display: none;
  }
  .title {
    color: white;
    position: fixed;
    left: 200px;
    top: 200px;
    font-size: 54px;
    padding: 2.5px 0px;
  }
  .title2 {
    color: white;
    font-size: 32px;
    position: fixed;
    left: 200px;
    top: 300px;
  }
  .login_div {
    position: fixed;
    right: 150px;
    top: 50%;
    transform: translateY(-50%);
    width: 480px;
    // height: 680px;
    background-color: rgba(255, 255, 238, 0.8);
    border-radius: 12px;
    overflow: hidden;
    padding: 40px 30px;
    font-size: 14px;
    text-align: center;
    box-shadow: 2px 3px 10px 10px #e8f0fe;
  }
  .login_way1 {
    display: inline-block;
    color: rebeccapurple;
    margin: 10px;
    background-color: rgb(176, 191, 250);
    padding: 10px;
    font-size: 20px;
    font-weight: 700;
    border-radius: 35px;
    cursor: pointer;
  }
  .login_way2 {
    display: inline-block;
    color: rebeccapurple;
    font-size: 16px;
    margin: 10px;
    padding: 10px;
    background-color: #e8f0fe;
    border-radius: 35px;
    cursor: pointer;
  }
  .hiden_way {
    display: none;
  }
  .input_span {
    width: 50px;
    height: 40px;
    display: inline-block;
    font-size: 14px;
    vertical-align: top;
    line-height: 40px;
    margin-right: 20px;
  }
  .input_css {
    padding: 0px 20px;
    width: 320px;
    height: 40px;
    font-size: 14px;
    vertical-align: top;
    outline: none;
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.8);
    outline: #e8f0fe;
  }
  .input_div {
    font-size: 0;
    margin: 20px 0px;
    position: relative;
    display: flex;
  }
  .input_code {
    margin-right: 80px;
    width: 120px;
  }
}
.bottom_div {
  display: flex;
  justify-content: space-evenly;
}
.to_regist {
  cursor: pointer;
  color: rgb(105, 157, 233);
}
</style>
